﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCPets.Extensions;
using MVCPets.Models;

namespace MVCPets
{
  /// <summary>
  /// Summary description for ImageHandler
  /// </summary>
  public class ImageHandler : IHttpHandler
  {

    public bool IsReusable { get { return true; } }

    public void ProcessRequest(HttpContext ctx)
    {
      var gd = ctx.Request.QueryString["id"].SafeParse<Guid>();
			var type = ctx.Request.QueryString["type"].SafeParse<string>() ?? "";

      if (gd != Guid.Empty)
      {
				if(type.Equals("Image", StringComparison.InvariantCultureIgnoreCase))
				{
					SendImage(ctx, gd);
				}
				else
				{
					SendPetImage(ctx, gd);
				}
      }

      ctx.Response.ContentType = "text/html";
      ctx.Response.Write("Image Not Found");
      ctx.Response.End();
    }

		private void SendImage(HttpContext ctx, Guid gd)
		{
			var foo = PetsModel.GetImage(gd);

			if (foo != null && foo.ImageData.Length > 0)
			{
				ctx.Response.ContentType = foo.ContentType;
				ctx.Response.OutputStream.Write(foo.ImageData, 0, foo.ImageData.Length);
				ctx.Response.End();
			}
		}

		private static void SendPetImage(HttpContext ctx, Guid gd)
		{
			var foo = PetsModel.GetThumbnail(gd);

			if (foo != null && foo.ImageData.Length > 0)
			{
				ctx.Response.ContentType = foo.ContentType;
				ctx.Response.OutputStream.Write(foo.ImageData, 0, foo.ImageData.Length);
				ctx.Response.End();
			}
		}
  }
}